<template>
    <view class="edit-order-container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <text class="nav-title">修改订单</text>
        </view>
        
        <!-- 表单区域 -->
        <view class="form-container" v-if="orderDetail">
            <!-- 基本信息 -->
            <view class="form-section">
                <view class="section-title">基本信息</view>
                
                <view class="form-item">
                    <text class="label">订单标题</text>
                    <input type="text" 
                        v-model="orderForm.title" 
                        placeholder="请输入订单标题"
                        class="input"
                        maxlength="50"
                    />
                </view>
                
                <view class="form-item">
                    <text class="label">编程语言</text>
                    <view class="language-selector">
                        <view 
                            v-for="(lang, index) in languageOptions" 
                            :key="index" 
                            class="language-tag" 
                            :class="{ 'selected': selectedLanguages.includes(lang) }"
                            @click="toggleLanguage(lang)"
                        >
                            {{ lang }}
                        </view>
                    </view>
                    <view class="selected-languages" v-if="orderForm.language">
                        <text class="selected-text">已选: {{ orderForm.language }}</text>
                    </view>
                </view>
                
                <view class="form-item budget-item">
                    <text class="label">预算范围</text>
                    <view class="budget-inputs">
                        <input type="digit" 
                            v-model="orderForm.lessBudget" 
                            placeholder="最低预算"
                            class="input budget-input"
                        />
                        <text class="separator">-</text>
                        <input type="digit" 
                            v-model="orderForm.highBudget" 
                            placeholder="最高预算"
                            class="input budget-input"
                        />
                    </view>
                </view>
                
                <view class="form-item">
                    <text class="label">期望完成天数</text>
                    <input type="number" 
                        v-model="orderForm.expectation" 
                        placeholder="请输入期望完成天数"
                        class="input"
                    />
                </view>
                
                <view class="form-item textarea-item">
                    <text class="label">订单需求描述</text>
                    <textarea 
                        v-model="orderForm.content" 
                        placeholder="请详细描述您的需求"
                        class="textarea"
                        maxlength="1000"
                    />
                    <text class="word-count">{{ orderForm.content.length }}/1000</text>
                </view>
            </view>
            
            <!-- 图片上传 -->
            <view class="form-section">
                <view class="section-title">参考图片</view>
                <view class="image-uploader">
                    <view class="image-list">
                        <view class="image-item" v-for="(image, index) in orderForm.imageList" :key="index">
                            <image :src="image" mode="aspectFill" class="preview-image"></image>
                            <view class="delete-btn" @click="removeImage(index)">×</view>
                        </view>
                        
                        <view class="upload-btn" @click="chooseImage" v-if="orderForm.imageList.length < 9">
                            <text class="upload-icon">+</text>
                            <text class="upload-text">上传图片</text>
                        </view>
                    </view>
                    <text class="tips">最多可上传9张图片，用于说明您的需求</text>
                </view>
            </view>
        </view>
        
        <!-- 加载状态 -->
        <view class="loading-state" v-if="isLoading">
            <view class="loading-spinner"></view>
            <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 提交按钮 -->
        <view class="button-container" v-if="!isLoading">
            <button class="submit-btn" @click="submitOrder" :disabled="isSubmitting">{{ isSubmitting ? '提交中...' : '保存修改' }}</button>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request.js'

// 获取页面参数
const orderId = ref('')

// 编程语言选项
const languageOptions = [
    'Java', 'Python', 'JavaScript', 'C++', 
    'C#', 'PHP', 'Go', 'Swift', 'Kotlin', 'Rust', 'Html',
    'Vue', 'Uniapp', 'React', 'Flutter', '微信小程序',
    'Android原生开发', 'IOS原生开发', '无要求', '其他'
]

// 已选择的语言
const selectedLanguages = ref([])

// 在页面加载前初始化
const initPage = () => {
    try {
        // 尝试从onLoad中获取参数
        const onLoadOptions = uni.getStorageSync('order_edit_options')
        if (onLoadOptions && onLoadOptions.id) {
            orderId.value = onLoadOptions.id
            console.log('从onLoad获取的订单ID:', orderId.value)
            fetchOrderDetail()
            return
        }
        
        // 获取当前页面路由
        const pages = getCurrentPages()
        if (!pages || pages.length === 0) {
            showError()
            return
        }
        
        const currentPage = pages[pages.length - 1]
        
        // 尝试多种方式获取页面参数
        if (currentPage.options && currentPage.options.id) {
            orderId.value = currentPage.options.id
            fetchOrderDetail()
            return
        }
        
        if (currentPage.$page && currentPage.$page.options && currentPage.$page.options.id) {
            orderId.value = currentPage.$page.options.id
            fetchOrderDetail()
            return
        }
        
        // 尝试从URL中解析
        const fullPath = currentPage.$page?.fullPath || currentPage.route
        if (fullPath && fullPath.includes('?')) {
            const queryString = fullPath.split('?')[1]
            const params = new URLSearchParams(queryString)
            orderId.value = params.get('id') || ''
            
            if (orderId.value) {
                fetchOrderDetail()
                return
            }
        }
        
        showError()
    } catch (error) {
        console.error('初始化页面参数失败:', error)
        showError()
    }
}

// 显示错误并返回
const showError = () => {
    uni.showToast({
        title: '订单ID不存在',
        icon: 'none'
    })
    setTimeout(() => {
        uni.navigateBack()
    }, 1500)
}

// 页面加载函数
onMounted(() => {
    initPage()
})

// 定义onLoad生命周期函数，用于接收页面参数
defineExpose({
    onLoad: (options) => {
        if (options && options.id) {
            // 将参数存储到本地，以便在mounted中使用
            uni.setStorageSync('order_edit_options', options)
            orderId.value = options.id
        }
    }
})

// 加载状态
const isLoading = ref(true)
const isSubmitting = ref(false)

// 订单详情
const orderDetail = ref(null)

// 表单数据
const orderForm = ref({
    title: '',
    language: '',
    lessBudget: '',
    highBudget: '',
    expectation: '',
    content: '',
    imageList: []
})

// 获取订单详情
const fetchOrderDetail = async () => {
    isLoading.value = true
    
    try {
        console.log('获取订单详情，ID:', orderId.value)
        
        const res = await request('/order/detail', {
            method: 'GET',
            data: {
                id: orderId.value
            }
        })
                
        if (res.code === 200 && res.data) {
            orderDetail.value = res.data
            
            // 填充表单数据
            orderForm.value = {
                title: res.data.title || '',
                language: res.data.language || '',
                lessBudget: res.data.lessBudget?.toString() || '',
                highBudget: res.data.highBudget?.toString() || '',
                expectation: res.data.expectation?.toString() || '',
                content: res.data.content || '',
                imageList: Array.isArray(res.data.imageList) ? res.data.imageList : []
            }
            
            // 设置已选择的语言
            if (orderForm.value.language) {
                selectedLanguages.value = orderForm.value.language.split(';')
            }
            
        } else {
            console.error('获取订单详情失败:', res)
            uni.showToast({
                title: res.msg || '获取订单详情失败',
                icon: 'none'
            })
            setTimeout(() => {
                uni.navigateBack()
            }, 1500)
        }
    } catch (error) {
        console.error('获取订单详情失败', error)
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
        })
    } finally {
        isLoading.value = false
    }
}

// 语言选择器变化
const toggleLanguage = (lang) => {
    const index = selectedLanguages.value.indexOf(lang)
    if (index === -1) {
        // 添加语言
        selectedLanguages.value.push(lang)
    } else {
        // 移除语言
        selectedLanguages.value.splice(index, 1)
    }
    
    // 更新表单中的语言字段，以分号分隔
    orderForm.value.language = selectedLanguages.value.join(';')
}

// 选择图片
const chooseImage = () => {
    uni.chooseImage({
        count: 9 - orderForm.value.imageList.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
            // 上传选中的图片
            const tempFilePaths = res.tempFilePaths
            tempFilePaths.forEach(path => {
                uploadImage(path)
            })
        }
    })
}

// 上传图片
const uploadImage = (filePath) => {
    uni.showLoading({
        title: '上传中...'
    })
    
    // 获取服务器基础URL
    const baseUrl = uni.getStorageSync('baseUrl') || 'http://127.0.0.1:8080'
    const uploadUrl = `${baseUrl}/system/uploadImg`
    
    uni.uploadFile({
        url: uploadUrl,
        filePath: filePath,
        name: 'file',
        header: {
            'sa-token': uni.getStorageSync('sa-token')
        },
        success: (uploadRes) => {
            try {
                const result = JSON.parse(uploadRes.data)
                if (result.code === 200) {
                    // 添加上传成功的图片URL到列表
                    const imgUrl = result.data
                    
                    // 调用添加订单图片接口
                    addOrderImage(imgUrl)
                } else {
                    uni.showToast({
                        title: result.msg || '上传失败',
                        icon: 'none'
                    })
                }
            } catch (e) {
                console.error('解析上传响应失败:', e)
                uni.showToast({
                    title: '上传失败，请重试',
                    icon: 'none'
                })
            }
        },
        fail: (error) => {
            console.error('上传失败:', error)
            uni.showToast({
                title: '上传失败，请重试',
                icon: 'none'
            })
        },
        complete: () => {
            uni.hideLoading()
        }
    })
}

// 添加订单图片
const addOrderImage = async (imgUrl) => {
    try {
        const res = await request('/order/addImg', {
            method: 'POST',
            data: {
                id: orderId.value,
                imgUrl: imgUrl
            }
        })
        
        if (res.code === 200) {
            // 添加到图片列表
            orderForm.value.imageList.push(imgUrl)
            uni.showToast({
                title: '图片添加成功',
                icon: 'success'
            })
        } else {
            uni.showToast({
                title: res.msg || '添加图片失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('添加订单图片失败', error)
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
        })
    }
}

// 移除图片
const removeImage = async (index) => {
    const imageUrl = orderForm.value.imageList[index]
    
    // 调用删除图片接口
    uni.showLoading({
        title: '删除中...'
    })
    
    try {
        const res = await request('/order/deleteImg', {
            method: 'POST',
            data: {
                id: orderId.value,
                imgUrl: imageUrl
            }
        })
        
        if (res.code === 200) {
            // 从列表中删除
            orderForm.value.imageList.splice(index, 1)
            uni.showToast({
                title: '删除成功',
                icon: 'success'
            })
        } else {
            uni.showToast({
                title: res.msg || '删除失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('删除图片失败', error)
        uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
        })
    } finally {
        uni.hideLoading()
    }
}

// 提交订单
const submitOrder = async () => {
    // 表单验证
    if (!orderForm.value.title.trim()) {
        uni.showToast({
            title: '请输入订单标题',
            icon: 'none'
        })
        return
    }
    
    if (!orderForm.value.language) {
        uni.showToast({
            title: '请选择编程语言',
            icon: 'none'
        })
        return
    }
    
    if (!orderForm.value.lessBudget || isNaN(Number(orderForm.value.lessBudget))) {
        uni.showToast({
            title: '请输入有效的最低预算',
            icon: 'none'
        })
        return
    }
    
    if (!orderForm.value.highBudget || isNaN(Number(orderForm.value.highBudget))) {
        uni.showToast({
            title: '请输入有效的最高预算',
            icon: 'none'
        })
        return
    }
    
    if (Number(orderForm.value.lessBudget) > Number(orderForm.value.highBudget)) {
        uni.showToast({
            title: '最低预算不能大于最高预算',
            icon: 'none'
        })
        return
    }
    
    if (!orderForm.value.expectation || isNaN(Number(orderForm.value.expectation))) {
        uni.showToast({
            title: '请输入有效的期望完成天数',
            icon: 'none'
        })
        return
    }
    
    if (!orderForm.value.content.trim()) {
        uni.showToast({
            title: '请输入订单需求描述',
            icon: 'none'
        })
        return
    }
    
    // 开始提交
    isSubmitting.value = true
    
    try {
        const res = await request('/order/update', {
            method: 'POST',
            data: {
                id: orderId.value,
                title: orderForm.value.title,
                language: orderForm.value.language,
                lessBudget: Number(orderForm.value.lessBudget),
                highBudget: Number(orderForm.value.highBudget),
                expectation: Number(orderForm.value.expectation),
                content: orderForm.value.content
            }
        })
        
        if (res.code === 200) {
            uni.showToast({
                title: '更新成功',
                icon: 'success'
            })
            
            // 返回上一页
            setTimeout(() => {
                uni.navigateBack()
            }, 1500)
        } else {
            uni.showToast({
                title: res.msg || '更新失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('更新订单失败', error)
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
        })
    } finally {
        isSubmitting.value = false
    }
}
</script>

<style lang="scss" scoped>
.edit-order-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #18122B 0%, #120C1C 100%);
    padding-bottom: 40rpx;
}

/* 导航栏样式 */
.nav-bar {
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #2D1457;
}

.nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #A259FF;
}

/* 表单容器 */
.form-container {
    padding: 20rpx 30rpx;
}

.form-section {
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    margin-top: 20rpx;
    padding: 30rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx #7B2FF244;
    border: 1px solid #2D1457;
}

.section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #A259FF;
    margin-bottom: 30rpx;
}

/* 表单项样式 */
.form-item {
    margin-bottom: 30rpx;
}

.label {
    display: block;
    font-size: 28rpx;
    color: #B8B8D1;
    margin-bottom: 16rpx;
}

.input {
    width: 100%;
    height: 80rpx;
    background: rgba(45, 20, 87, 0.3);
    border: 1px solid #2D1457;
    border-radius: 12rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    color: #fff;
}

/* 选择器样式 */
.picker-view {
    width: 100%;
    height: 80rpx;
    background: rgba(45, 20, 87, 0.3);
    border: 1px solid #2D1457;
    border-radius: 12rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.arrow {
    font-size: 24rpx;
    color: #7B2FF2;
}

/* 预算范围 */
.budget-item {
    margin-bottom: 30rpx;
}

.budget-inputs {
    display: flex;
    align-items: center;
}

.budget-input {
    flex: 1;
}

.separator {
    margin: 0 20rpx;
    color: #B8B8D1;
}

.textarea-item {
    position: relative;
}

.textarea {
    width: 100%;
    height: 240rpx;
    background: rgba(45, 20, 87, 0.3);
    border: 1px solid #2D1457;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #fff;
}

.word-count {
    position: absolute;
    bottom: 20rpx;
    right: 20rpx;
    font-size: 24rpx;
    color: #B8B8D1;
}

/* 图片上传区域 */
.image-uploader {
    margin-top: 20rpx;
}

.image-list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
}

.image-item {
    position: relative;
    aspect-ratio: 1/1;
    border-radius: 12rpx;
    overflow: hidden;
    border: 1px solid #2D1457;
}

.preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.delete-btn {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    width: 44rpx;
    height: 44rpx;
    background: rgba(0, 0, 0, 0.6);
    color: #fff;
    border-radius: 22rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 32rpx;
}

.upload-btn {
    aspect-ratio: 1/1;
    background: rgba(45, 20, 87, 0.3);
    border: 1px dashed #7B2FF2;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.upload-icon {
    font-size: 48rpx;
    color: #7B2FF2;
    margin-bottom: 10rpx;
}

.upload-text {
    font-size: 24rpx;
    color: #B8B8D1;
}

.tips {
    font-size: 24rpx;
    color: #B8B8D1;
    margin-top: 20rpx;
}

/* 按钮样式 */
.button-container {
    padding: 40rpx 30rpx;
}

.submit-btn {
    background: linear-gradient(45deg, #7B2FF2, #10AEFF);
    color: #fff;
    font-size: 32rpx;
    padding: 20rpx 0;
    border-radius: 12rpx;
    text-align: center;
    border: none;
    box-shadow: 0 4rpx 16rpx #7B2FF244;
}

.submit-btn:active {
    opacity: 0.8;
}

.submit-btn[disabled] {
    background: #2D1457;
    opacity: 0.7;
}

/* 加载状态 */
.loading-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 400rpx;
}

.loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid rgba(162, 89, 255, 0.2);
    border-top: 4rpx solid #A259FF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
}

.loading-text {
    font-size: 28rpx;
    color: #B8B8D1;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 语言选择器样式 */
.language-selector {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-bottom: 20rpx;
}

.language-tag {
    padding: 10rpx 20rpx;
    background: rgba(45, 20, 87, 0.3);
    border: 1px solid #2D1457;
    border-radius: 30rpx;
    font-size: 26rpx;
    color: #B8B8D1;
    transition: all 0.3s;
}

.language-tag.selected {
    background: rgba(123, 47, 242, 0.3);
    border-color: #7B2FF2;
    color: #fff;
}

.selected-languages {
    margin-top: 10rpx;
}

.selected-text {
    font-size: 24rpx;
    color: #6069f0; 
}
</style>